<template>
  <div class="page-container">
    <h1 class="metro-title"><i class="metro-icon"></i>数据分析</h1>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>地铁线路分析</span>
            </div>
          </template>
          <div ref="lineAnalysisChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>地铁站点分析</span>
            </div>
          </template>
          <div ref="stationAnalysisChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>地铁客流量分析</span>
            </div>
          </template>
          <div ref="passengerAnalysisChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Query from '@arcgis/core/rest/support/Query.js'

// 图表DOM引用
const lineAnalysisChartRef = ref<HTMLElement | null>(null)
const stationAnalysisChartRef = ref<HTMLElement | null>(null)
const passengerAnalysisChartRef = ref<HTMLElement | null>(null)

// 图表实例
let lineAnalysisChart: echarts.ECharts | null = null
let stationAnalysisChart: echarts.ECharts | null = null
let passengerAnalysisChart: echarts.ECharts | null = null

// 初始化图表
function initCharts() {
  // 地铁线路分析图表 - 线路长度与站点数量对比
  if (lineAnalysisChartRef.value) {
    lineAnalysisChart = echarts.init(lineAnalysisChartRef.value)
    lineAnalysisChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['站点数量', '线路长度(km)']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '站点数量',
          position: 'left'
        },
        {
          type: 'value',
          name: '线路长度(km)',
          position: 'right'
        }
      ],
      series: [
        {
          name: '站点数量',
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#1976d2'
          }
        },
        {
          name: '线路长度(km)',
          type: 'line',
          yAxisIndex: 1,
          data: [],
          itemStyle: {
            color: '#ff9800'
          },
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3
          }
        }
      ]
    })
  }

  // 地铁站点分析图表 - 站点类型与客流量关系
  if (stationAnalysisChartRef.value) {
    stationAnalysisChart = echarts.init(stationAnalysisChartRef.value)
    stationAnalysisChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: ['普通站', '换乘站', '终点站']
      },
      series: [
        {
          name: '站点类型分布',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 0, name: '普通站' },
            { value: 0, name: '换乘站' },
            { value: 0, name: '终点站' }
          ]
        }
      ]
    })
  }

  // 地铁客流量分析图表 - 按时段分布
  if (passengerAnalysisChartRef.value) {
    passengerAnalysisChart = echarts.init(passengerAnalysisChartRef.value)
    passengerAnalysisChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['工作日', '周末']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['6:00-9:00', '9:00-12:00', '12:00-15:00', '15:00-18:00', '18:00-21:00', '21:00-24:00']
      },
      yAxis: {
        type: 'value',
        name: '客流量(万人次)'
      },
      series: [
        {
          name: '工作日',
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#4caf50'
          }
        },
        {
          name: '周末',
          type: 'bar',
          data: [],
          itemStyle: {
            color: '#e91e63'
          }
        }
      ]
    })
  }
}

// 加载分析数据
async function loadAnalysisData() {
  try {
    // 创建地铁线路图层
    const subwayLineLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/1',
      outFields: ['*']
    })

    // 创建地铁站点图层
    const subwayStationLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/0',
      outFields: ['*']
    })

    // 查询所有线路
    const lineQuery = new Query()
    lineQuery.where = '1=1'
    lineQuery.outFields = ['*']
    const lineResults = await subwayLineLayer.queryFeatures(lineQuery)
    const lines = lineResults.features

    // 查询所有站点
    const stationQuery = new Query()
    stationQuery.where = '1=1'
    stationQuery.outFields = ['*']
    const stationResults = await subwayStationLayer.queryFeatures(stationQuery)
    const stations = stationResults.features

    // 更新地铁线路分析图表
    if (lineAnalysisChart) {
      const lineNames = lines.map(line => line.attributes.LineName)
      const stationCounts = lines.map(line => line.attributes.StationCount || 0)

      // 模拟线路长度数据（实际应用中应从数据库获取）
      const lineLengths = lines.map(line => {
        // 这里使用随机数模拟线路长度，实际应用中应使用真实数据
        return (Math.random() * 30 + 10).toFixed(1)
      })

      lineAnalysisChart.setOption({
        xAxis: {
          data: lineNames
        },
        series: [
          {
            name: '站点数量',
            data: stationCounts
          },
          {
            name: '线路长度(km)',
            data: lineLengths
          }
        ]
      })
    }

    // 更新地铁站点分析图表
    if (stationAnalysisChart) {
      const stationTypes = {
        普通站: 0,
        换乘站: 0,
        终点站: 0
      }

      stations.forEach(station => {
        const type = station.attributes.StationType
        if (type in stationTypes) {
          stationTypes[type as keyof typeof stationTypes]++
        }
      })

      stationAnalysisChart.setOption({
        series: [
          {
            data: [
              { value: stationTypes['普通站'], name: '普通站' },
              { value: stationTypes['换乘站'], name: '换乘站' },
              { value: stationTypes['终点站'], name: '终点站' }
            ]
          }
        ]
      })
    }

    // 更新地铁客流量分析图表
    if (passengerAnalysisChart) {
      // 模拟不同时段的客流量数据（实际应用中应从数据库获取）
      const workdayData = [45, 20, 25, 30, 50, 15]
      const weekendData = [20, 30, 40, 35, 25, 10]

      passengerAnalysisChart.setOption({
        series: [
          {
            name: '工作日',
            data: workdayData
          },
          {
            name: '周末',
            data: weekendData
          }
        ]
      })
    }
  } catch (error) {
    console.error('加载分析数据失败:', error)
  }
}

// 窗口大小变化时重新调整图表大小
function handleResize() {
  lineAnalysisChart?.resize()
  stationAnalysisChart?.resize()
  passengerAnalysisChart?.resize()
}

onMounted(() => {
  // 初始化图表
  initCharts()

  // 加载数据
  loadAnalysisData()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  lineAnalysisChart?.dispose()
  stationAnalysisChart?.dispose()
  passengerAnalysisChart?.dispose()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.metro-title {
  margin-bottom: 20px;
  color: #1976d2;
  font-size: 24px;
  display: flex;
  align-items: center;
}

.metro-icon {
  display: inline-block;
  width: 24px;
  height: 24px;
  margin-right: 8px;
  background-color: #1976d2;
  border-radius: 50%;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
}

.chart-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
}
</style>